package com.jbm.jbmsupplier.zp.liaotian;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.weather.myframe.PopupSelectImage;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jbm.jbmsupplier.R;
import com.jbm.jbmsupplier.activity.AllActivityApp;
import com.jbm.jbmsupplier.zp.IndexBar.widget.RecordButton;
import com.jbm.jbmsupplier.zp.adapters.ChatMsgViewAdapter;
import com.jbm.jbmsupplier.zp.adapters.MainGridAdapter;
import com.jbm.jbmsupplier.zp.entity.Buddy_ListData;
import com.jbm.jbmsupplier.zp.entity.ChatMsgEntity;
import com.jbm.jbmsupplier.zp.entity.Recent_ContactsData;
import com.jbm.jbmsupplier.zp.factory.FactotySecndMode;
import com.jbm.jbmsupplier.zp.presenters.MainActivityS;
import com.jbm.jbmsupplier.zp.sqldata.MySqliteUtlis;
import com.jbm.jbmsupplier.zp.utils.AudioRecorder;
import com.jbm.jbmsupplier.zp.utils.KeyboardLayout;
import com.jbm.jbmsupplier.zp.views.MainViews;

import java.io.File;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import static com.jbm.jbmsupplier.zp.utils.TableName.sendIndex;

public class MainActivity extends AllActivityApp implements OnClickListener, View.OnLayoutChangeListener, MainViews {
    @InjectView(R.id.pull_refresh_list)
    PullToRefreshListView pullRefreshList;
    @InjectView(R.id.teleft)
    TextView teleft;
    @InjectView(R.id.tetitle)
    TextView tetitle;
    @InjectView(R.id.toolbar_image)
    ImageView toolbarImage;
    /**
     * Called when the activity is first created.
     */
    private ImageButton mBtnSend;
    private ImageButton btn_more;
    private RecordButton mBtnRcd;
    private EditText mEditTextContent;
    private RelativeLayout mBottom;
    private ListView mListView;
    private ChatMsgViewAdapter mAdapter;
    private LinearLayout voice_rcd_hint_loading, voice_rcd_hint_rcding, voice_rcd_hint_tooshort;
    private ImageView img1, sc_img1;
    private SoundMeter mSensor;
    private LinearLayout del_re;
    private ImageView chatting_mode_btn, volume;
    private boolean btn_vocie = false;
    private int flag = 1;
    private LinearLayout ll_more;
    private String mEditText;
    private MySqliteUtlis sql;
    //Activity最外层的Layout视图
    private LinearLayout activityRootView;
    private GridView hidder_gv;
    //屏幕高度
    private int screenHeight = 0;
    private int keyHeight = 0;
    private FactotySecndMode factotySecndMode;
    private String contString;
    private File files;
    private int to_id;
    private String toname;
    private int page;
    private int num = 5;
    int mKeyboardHeight = 400; // 输入法默认高度为400
    private KeyboardLayout mKeyboardLayout;
    private MainActivityS mainActivityS;
    public static int cgid;
    private int tag;

    // 设置表情栏的高度
    private void initEmojiView() {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) ll_more.getLayoutParams();
        layoutParams.height = mKeyboardHeight;
        ll_more.setLayoutParams(layoutParams);
    }

    @Override
    public int setContentView() {
        return R.layout.chat;
    }

    @Override
    public void initIalizeView() {
        ButterKnife.inject(this);
        // 启动activity时不自动弹出软键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        //获取屏幕高度
        screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight / 3;
        mainActivityS = new MainActivityS(this, this);
        Intent intent = getIntent();
        Buddy_ListData UserData = (Buddy_ListData) intent.getSerializableExtra("main");
        Recent_ContactsData UserDatas = (Recent_ContactsData) intent.getSerializableExtra("mais");
        if (UserData != null) {
            to_id = UserData.getM_account_id();
            toname = UserData.getNickname();
        }
        /**
         * 在消息页面传入数据过来
         * tag  如果等于1  那就是群的消息
         */
        if (UserDatas != null) {
            to_id = UserDatas.getTo_id();
            toname = UserDatas.getName();
            cgid = UserDatas.getCgid();
            tag = UserDatas.getTag();

        }


/**
 * 此方法
 * 初始化数据
 * 和
 * 更新聊天的数据
 * 群和好友的消息
 *
 *
 */
        if (tag == 1) {
            mainActivityS.InitData(cgid, toname, tag);
        } else {
            mainActivityS.InitData(to_id, toname, tag);
        }
        mainActivityS.InitView();
        mainActivityS.LoadAdapterData(0, 0, tag);//加载聊天记录
    }

    private void pullUpRefresh() {
        pullRefreshList.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {//预加载
                page += 5;
//                initData(page,num);
            }
        });
        pullRefreshList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {//下拉
                page = 0;
//                initData(page,num);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {//上拉
                page += 5;
//                initData(page,num);
            }

        });

    }


    @Override
    public void onBackPressed() {
        sendBroad();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING); //  不改变布局，隐藏键盘，emojiView弹出
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mEditTextContent.getApplicationWindowToken(), 0);
        finish();
        super.onBackPressed();
    }


    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.btn_send:
                contString = mEditTextContent.getText().toString();
                if (contString.length() > 0) {
                    mainActivityS.SendText(contString, to_id, tag, cgid);
                }//发送文本
                break;
            case R.id.teleft:

                break;
        }
    }

    public void sendBroad() {
        Intent intent = new Intent();
        intent.putExtra("messageFlag", 50);
        intent.setAction("MSG");
        getApplicationContext().sendBroadcast(intent);
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
//			Toast.makeText(MainActivity.this, "监听到软键盘弹起...", Toast.LENGTH_SHORT).show();
        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
//			Toast.makeText(MainActivity.this, "监听到软件盘关闭...", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            //选择图片回调
            case 100:
                files = (File) data.getSerializableExtra("file");
                mainActivityS.SendPic(to_id, files.getAbsolutePath(), files.getName(), tag, cgid);//发送图片
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //添加layout大小发生改变监听器
        activityRootView.addOnLayoutChangeListener(this);
    }

    @Override
    public void InitView() {//初始化数据
        mListView = (ListView) findViewById(R.id.listview);
        mBtnSend = (ImageButton) findViewById(R.id.btn_send);
        mBtnRcd = (RecordButton) findViewById(R.id.btn_rcd);
        mBtnSend.setOnClickListener(this);
        mBottom = (RelativeLayout) findViewById(R.id.btn_bottom);
        chatting_mode_btn = (ImageView) this.findViewById(R.id.ivPopUp);
        volume = (ImageView) this.findViewById(R.id.volume);
        img1 = (ImageView) this.findViewById(R.id.img1);
        sc_img1 = (ImageView) this.findViewById(R.id.sc_img1);
        del_re = (LinearLayout) this.findViewById(R.id.del_re);
        btn_more = (ImageButton) findViewById(R.id.btn_more);
        //这个是功能列表
        hidder_gv = (GridView) findViewById(R.id.hidder_gv);
        hidder_gv.setAdapter(new MainGridAdapter(this));
        activityRootView = (LinearLayout) findViewById(R.id.ll_bottom);
        voice_rcd_hint_rcding = (LinearLayout) this.findViewById(R.id.voice_rcd_hint_rcding);
        voice_rcd_hint_loading = (LinearLayout) this.findViewById(R.id.voice_rcd_hint_loading);
        voice_rcd_hint_tooshort = (LinearLayout) this.findViewById(R.id.voice_rcd_hint_tooshort);
        ll_more = (LinearLayout) findViewById(R.id.LL_More);
        mEditTextContent = (EditText) findViewById(R.id.et_sendmessage);
        chatting_mode_btn.setImageResource(R.mipmap.voice);
        mSensor = new SoundMeter();
        //点击下面功能的操作
        tetitle.setText(toname);
    }

    @Override
    public void setOnclickListenr() {//监听
        hidder_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
//							//请求图片
                        startActivityForResult(new Intent(MainActivity.this, PopupSelectImage.class), 100);
                        break;
//						case 1:
//							break;
//						case 1:
//							new ALpayUtil(MainActivity.this, MainActivity.this, new ALpayUtil.SuccessListener() {
//								@Override
//								public void sucess(String str) {
//									hint(str);
//								}
//
//								@Override
//								public void fail(String str) {
//									hint(str);
//								}
//
//								@Override
//								public void getError(String str) {
//									hint(str);
//								}
//							}).chong(0.1,"1234567889");
//							Toast.makeText(MainActivity.this,"支付",Toast.LENGTH_SHORT).show();
//							break;
//						case 3:
//							Toast.makeText(MainActivity.this,"商品列表",Toast.LENGTH_SHORT).show();
//							break;
                }
            }
        });
        //输入框点击监听
        mEditTextContent.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mKeyboardLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ll_more.setVisibility(View.GONE);
                        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                    }
//					}
                }, 250); // 延迟一段时间，等待输入法完全弹出


            }
        });

        //输入框变动监听
        mEditTextContent.addTextChangedListener(watcher);
        //语音文字切换按钮
        chatting_mode_btn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                if (btn_vocie) {
                    mBtnRcd.setVisibility(View.GONE);
                    mEditTextContent.setVisibility(View.VISIBLE);
                    btn_vocie = false;
                    chatting_mode_btn.setImageResource(R.mipmap.voice);
                } else {
                    mBtnRcd.setVisibility(View.VISIBLE);
                    mEditTextContent.setVisibility(View.GONE);
                    chatting_mode_btn.setImageResource(R.mipmap.keybord);
                    btn_vocie = true;
                    if (mKeyboardLayout.isKeyboardActive()) {
                        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING); //  不改变布局，隐藏键盘，emojiView弹出
                        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(mEditTextContent.getApplicationWindowToken(), 0);
                        ll_more.setVisibility(View.GONE);
                    } else {
                        ll_more.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    //文本框实时监听
    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        //输入文字后的状态
        @Override
        public void afterTextChanged(Editable s) {
            mEditText = mEditTextContent.getText().toString();
            if (mEditText.equals("")) {
                mBtnSend.setVisibility(View.GONE);
                btn_more.setVisibility(View.VISIBLE);
            } else {
                mBtnSend.setVisibility(View.VISIBLE);
                btn_more.setVisibility(View.INVISIBLE);
            }
        }
    };

    @Override
    public void LoadData(ChatMsgEntity message) {//接收广播传过来的消息
        sendIndex += 1;
        mAdapter.notifyData(message, mListView.getLastVisiblePosition());
    }

    @Override
    public void LoadOut() {//加载输入框
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        mKeyboardLayout = (KeyboardLayout) findViewById(R.id.keyboard_layout);
        mKeyboardLayout.setKeyboardListener(new KeyboardLayout.KeyboardLayoutListener() {
            @Override
            public void onKeyboardStateChanged(boolean isActive, int keyboardHeight) {
                if (isActive) { // 输入法打开
                    if (mKeyboardHeight != keyboardHeight) { // 键盘发生改变时才设置emojiView的高度，因为会触发onGlobalLayoutChanged，导致onKeyboardStateChanged再次被调用
                        mKeyboardHeight = keyboardHeight;
                        initEmojiView(); // 每次输入法弹起时，设置emojiView的高度为键盘的高度，以便下次emojiView弹出时刚好等于键盘高度
                    }
                    if (btn_more.isSelected()) { // 表情打开状态下
                        ll_more.setVisibility(View.GONE);
                        btn_more.setSelected(false);
                    }
                }
            }
        });


        btn_more.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_more.setSelected(!btn_more.isSelected());
                if (mKeyboardLayout.isKeyboardActive()) { // 输入法打开状态下
                    if (btn_more.isSelected()) { // 打开表情
                        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING); //  不改变布局，隐藏键盘，emojiView弹出
                        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(mEditTextContent.getApplicationWindowToken(), 0);
                        ll_more.setVisibility(View.VISIBLE);
                    } else {
                        ll_more.setVisibility(View.GONE);
                        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(mEditTextContent.getApplicationWindowToken(), 0);
                        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                    }
                } else { //  输入法关闭状态下
                    if (btn_more.isSelected()) {
                        // 设置为不会调整大小，以便输入弹起时布局不会改变。若不设置此属性，输入法弹起时布局会闪一下
                        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
                        ll_more.setVisibility(View.VISIBLE);
                    } else {
                        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                        ll_more.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    @Override
    public void LoadAdapterData(List<ChatMsgEntity> mDataArrays, int foid) {//加载查找的聊天记录

        mAdapter = new ChatMsgViewAdapter(this, mDataArrays, to_id, foid, new ChatMsgViewAdapter.JumpInterface() {
            @Override
            public void scroll() {
                mListView.setSelection(mListView.getBottom());
            }

            @Override
            public void setonClickSend(final String tag, final String name, final String date, final int cgid, final int tags) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        mainActivityS.SendErrorData(tag, name, date, cgid, tags);
                    }
                }).start();

            }
        });
        sendIndex = mDataArrays.size() - 1;
        mListView.setAdapter(mAdapter);
//        if (pullRefreshList!=null){
//            pullRefreshList.onRefreshComplete();}
        AudioRecorder audios = new AudioRecorder(to_id, mAdapter, foid, toname, mListView, MainActivity.this, mDataArrays, tag);
        mBtnRcd.setAudioRecord(audios);
    }

    @Override
    public void LoadErrorMassage(List<ChatMsgEntity> mDataArrays) {//加载错误数据
        mAdapter.notifyData(mDataArrays);
    }

    @Override
    public void SendText(ChatMsgEntity entity, int tag) {//发送失败信息成功后更新
        if (tag == 1) {
            mAdapter.notifyData(entity);
            mListView.setSelection(mListView.getCount() - 1);
            mEditTextContent.setText("");
        } else if (tag == 2) {
            mAdapter.notifyData(entity);
            mListView.setSelection(mListView.getCount() - 1);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mainActivityS.onDestroy();//关闭广播
        if (mAdapter != null) {
            mAdapter.killMediaPlayer();
        }
    }


    @OnClick({R.id.teleft, R.id.toolbar_image})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.teleft:
                sendBroad();
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING); //  不改变布局，隐藏键盘，emojiView弹出
                InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mEditTextContent.getApplicationWindowToken(), 0);

                finish();
                break;
            case R.id.toolbar_image:



                break;
        }
    }
}